package com.augmentum.oes.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.augmentum.oes.Constants;
import com.augmentum.oes.model.User;
import com.augmentum.oes.util.PathUtil;

public class SessionFilter implements Filter {

    private static final String TIP_MSG = "Please login to your account!";
    private String noNeedLoginPage;
    protected FilterConfig filterConfig;

    @Override
    public void destroy() {
        //empty
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String uri = request.getRequestURI();
        String requestedUri = uri.substring(request.getContextPath().length()+1);
        String[] pages = noNeedLoginPage.split(",");

        boolean isAllow = false;
        for (String page : pages) {
            if (page.equals(requestedUri)) {
                isAllow = true;
                break;
            }
            if (requestedUri.endsWith(".css") || requestedUri.endsWith(".js") || requestedUri.endsWith(".png") || requestedUri.endsWith(".jpg")) {
                isAllow = true;
                break;
            }
        }
        if (isAllow) {
            chain.doFilter(request, response);
        } else {
            HttpSession session = request.getSession();
            User user = (User)session.getAttribute(Constants.USER);
            if (user != null) {
                chain.doFilter(request, response);
            } else {
                session.setAttribute(Constants.NO_LOGIN_MSG, TIP_MSG);
                response.sendRedirect(PathUtil.getFullPath("login.action"));
            }
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        if (filterConfig.getInitParameter("noNeedLoginPage") != null) {
            noNeedLoginPage = filterConfig.getInitParameter("noNeedLoginPage");
        }
    }

}
